<template>
  <div>
    <div style="border: 1px solid #ccc; margin-top: 10px;">
      <Toolbar
          :defaultConfig="toolbarConfig"
          :editor="editorRef"
          style="border-bottom: 1px solid #ccc"
      />
      <Editor
          v-model="valueHtml"
          :defaultConfig="editorConfig"
          style="height: 200px; overflow-y: hidden;"
          @onChange="handleChange"
          @onCreated="handleCreated"
          @onPaste="handlePaste"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, shallowRef, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { photoUploadFileAPI } from "@/api/upload";

// 编辑器实例，必须用 shallowRef，重要！
const editorRef = shallowRef<InstanceType<typeof Editor> | null>(null)

// 内容 HTML
const valueHtml = ref('')

const props = defineProps({
  content: {
    type: String,
    default: '<p></p>',
  },
})

// 模拟 ajax 异步获取内容
onMounted(() => {
  valueHtml.value = props.content
})

let oldVal = ""
watch(() => props.content, (val: string) => {
  if (val !== oldVal) {
    valueHtml.value = val
    oldVal = val
  }
},{immediate: true, deep:true})

const toolbarConfig: any = {
  excludeKeys: ["insertImage", "group-video"] //去掉网络上传图片和上传视频
}

const editorConfig: any = {
  placeholder: '请输入内容...',
  MENU_CONF:{
    uploadImage:{
      // 自定义上传
      async customUpload(file: any, insertFn: any) {
        photoUploadFileAPI(file).then((response: any) => {
          // 假设 response.data.url 是服务器返回的图片 URL
          const url = `http://localhost:8018/file/image?imageName=${encodeURIComponent(response.data.url)}`;
          insertFn(url); // 插入图片到编辑器中
        }).catch((error: any) => {
          console.error('图片上传失败', error);
        });
      },
    },
    pasteFilterStyle: false, // 禁止粘贴样式
    pasteIgnoreImg: false, // 允许粘贴图片
  }
}

// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 编辑器回调函数
const handleCreated = (editor: InstanceType<typeof Editor>) => {
  // valueHtml.value = ""
  editorRef.value = editor // 记录 editor 实例，重要！

  // 使用 nextTick 确保 DOM 更新完成后再设置内容
  nextTick(() => {
    valueHtml.value = oldVal;
  });
}

const emit = defineEmits(['setContent'])

const handleChange = () => {
  emit('setContent', valueHtml.value)
}

// 处理粘贴事件
const handlePaste = (editor: InstanceType<typeof Editor>, event: ClipboardEvent) => {
  const items = (event.clipboardData || window.clipboardData).items;
  let blob = null;

  for (let i = 0; i < items.length; i++) {
    if (items[i].type.indexOf("image") !== -1) {
      blob = items[i].getAsFile();
      break;
    }
  }

  if (blob) {
    const formData = new FormData();
    formData.append('file', blob);

    photoUploadFileAPI(formData).then((response: any) => {
      const url = `http://localhost:8018/file/image?imageName=${encodeURIComponent(response.data.url)}`;
      editor.insertText(`<img src="${url}" alt="Pasted Image" />`);
    }).catch((error: any) => {
      console.error('粘贴图片上传失败', error);
    });

    event.preventDefault(); // 阻止默认粘贴行为
  }
}
</script>

<style scoped>

</style>